package com.demo.accessibilitykeeper;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

/**
 * Description:网络状态变化广播接收器
 *  * 监听网络连接和断开事件
 * Author: dengpao
 * Date: 2025/9/19 13:58
 */
public class NetworkReceiver extends BroadcastReceiver {


    private static final String TAG = "NetworkReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.d(TAG, "NetworkReceiver onReceive, action: " + action);

        if (action == null) {
            return;
        }

        if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            handleConnectivityChange(context);
        }
    }

    /**
     * 处理网络连接变化
     */
    private void handleConnectivityChange(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
            return;
        }

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

        if (isConnected) {
            handleNetworkConnected(context, activeNetwork);
        } else {
            handleNetworkDisconnected(context);
        }
    }

    /**
     * 处理网络连接
     */
    private void handleNetworkConnected(Context context, NetworkInfo networkInfo) {
        String networkType = getNetworkTypeName(networkInfo.getType());
        Log.i(TAG, "🌐 NETWORK_CONNECTED - Type: " + networkType);

        // 网络恢复时的操作
        onNetworkRestored(context);

        // 记录网络连接事件
        recordNetworkEvent(context, "connected", networkType);
    }

    /**
     * 处理网络断开
     */
    private void handleNetworkDisconnected(Context context) {
        Log.w(TAG, "❌ NETWORK_DISCONNECTED - No network connection");

        // 网络断开时的操作
        onNetworkLost(context);

        // 自动尝试连接网络
        attemptAutoReconnect(context);

        // 记录网络断开事件
        recordNetworkEvent(context, "disconnected", "none");
    }

    /**
     * 尝试自动重新连接网络
     */
    private void attemptAutoReconnect(Context context) {
        Log.d(TAG, "🔄 ATTEMPTING_AUTO_RECONNECT");

        // 延迟一段时间后尝试连接（避免频繁操作）
        new android.os.Handler(context.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                // 再次检查是否仍然断网
                if (!NetworkManager.isNetworkAvailable(context)) {
                    Log.d(TAG, "⏰ DELAYED_RECONNECT_ATTEMPT - Still disconnected");
                    NetworkManager.tryConnectNetwork(context);
                } else {
                    Log.d(TAG, "✅ NETWORK_RECOVERED_BEFORE_RECONNECT");
                }
            }
        }, 5000); // 5秒后尝试
    }

    /**
     * 网络恢复时的处理
     */
    private void onNetworkRestored(Context context) {
        try {
            Log.d(TAG, "🔄 NETWORK_RESTORED - Performing recovery operations");

            // 1. 重启服务确保正常运行
            restartServices(context);

            // 2. 同步数据（如果有）
            syncData(context);

            // 3. 发送网络恢复广播
            sendNetworkStatusBroadcast(context, true);

        } catch (Exception e) {
            Log.e(TAG, "Error in network restored handling", e);
        }
    }

    /**
     * 网络断开时的处理
     */
    private void onNetworkLost(Context context) {
        try {
            Log.d(TAG, "🔴 NETWORK_LOST - Performing disconnect operations");

            // 1. 暂停网络相关操作
            pauseNetworkOperations(context);

            // 2. 保存状态
            saveNetworkState(context);

            // 3. 发送网络断开广播
            sendNetworkStatusBroadcast(context, false);

        } catch (Exception e) {
            Log.e(TAG, "Error in network lost handling", e);
        }
    }

    /**
     * 重启服务
     */
    private void restartServices(Context context) {
        try {
            Log.d(TAG, "🔄 RESTARTING_SERVICES_AFTER_NETWORK_RECOVERY");

            Intent keepAliveIntent = new Intent(context, KeepAliveService.class);
            context.startService(keepAliveIntent);

            Intent foregroundIntent = new Intent(context, ForegroundService.class);
            context.startService(foregroundIntent);

        } catch (Exception e) {
            Log.e(TAG, "Error restarting services", e);
        }
    }

    /**
     * 同步数据
     */
    private void syncData(Context context) {
        // 这里可以添加数据同步逻辑
        Log.d(TAG, "📡 SYNCING_DATA_AFTER_NETWORK_RECOVERY");
    }

    /**
     * 暂停网络操作
     */
    private void pauseNetworkOperations(Context context) {
        // 这里可以暂停网络请求等操作
        Log.d(TAG, "⏸️ PAUSING_NETWORK_OPERATIONS");
    }

    /**
     * 保存网络状态
     */
    private void saveNetworkState(Context context) {
        try {
            context.getSharedPreferences("network_prefs", Context.MODE_PRIVATE)
                    .edit()
                    .putLong("last_network_disconnect_time", System.currentTimeMillis())
                    .apply();
        } catch (Exception e) {
            Log.e(TAG, "Error saving network state", e);
        }
    }

    /**
     * 发送网络状态广播
     */
    private void sendNetworkStatusBroadcast(Context context, boolean isConnected) {
        try {
            Intent intent = new Intent("com.demo.accessibilitykeeper.NETWORK_STATUS_CHANGED");
            intent.putExtra("is_connected", isConnected);
            intent.putExtra("timestamp", System.currentTimeMillis());
            context.sendBroadcast(intent);

            Log.d(TAG, "📡 NETWORK_STATUS_BROADCAST_SENT - Connected: " + isConnected);
        } catch (Exception e) {
            Log.e(TAG, "Error sending network status broadcast", e);
        }
    }

    /**
     * 记录网络事件
     */
    private void recordNetworkEvent(Context context, String eventType, String networkType) {
        try {
            context.getSharedPreferences("network_prefs", Context.MODE_PRIVATE)
                    .edit()
                    .putString("last_network_event", eventType)
                    .putString("last_network_type", networkType)
                    .putLong("last_network_event_time", System.currentTimeMillis())
                    .apply();
        } catch (Exception e) {
            Log.e(TAG, "Error recording network event", e);
        }
    }

    /**
     * 获取网络类型名称
     */
    private static String getNetworkTypeName(int type) {
        switch (type) {
            case ConnectivityManager.TYPE_WIFI:
                return "WiFi";
            case ConnectivityManager.TYPE_MOBILE:
                return "Mobile";
            case ConnectivityManager.TYPE_ETHERNET:
                return "Ethernet";
            case ConnectivityManager.TYPE_VPN:
                return "VPN";
            case ConnectivityManager.TYPE_BLUETOOTH:
                return "Bluetooth";
            default:
                return "Unknown";
        }
    }

    /**
     * 检查当前网络状态
     */
    public static boolean isNetworkAvailable(Context context) {
        try {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cm == null) {
                return false;
            }

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
        } catch (Exception e) {
            Log.e(TAG, "Error checking network availability", e);
            return false;
        }
    }

    /**
     * 获取当前网络类型
     */
    public static String getCurrentNetworkType(Context context) {
        try {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cm == null) {
                return "none";
            }

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            if (activeNetwork == null || !activeNetwork.isConnectedOrConnecting()) {
                return "none";
            }

            return getNetworkTypeName(activeNetwork.getType());
        } catch (Exception e) {
            Log.e(TAG, "Error getting network type", e);
            return "unknown";
        }
    }

}
